<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;

class Order extends Frontend {

    //补货
    public function index() {
        $box_info = db('user_box')->where(['user_id' => $this->iUserId, 'status' => 1])->find();

        if ($box_info) {
            
        } else {
            $this->redirect(url('nobox'));
        }
    }

    public function add() {
        $is_score = $this->request->param('is_score', 0);
        $coupon_id = $this->request->param('coupon_id', 0);

        $cart_goods = db('cart')
                ->field('box_goods_id,buy_num')
                ->where(['user_id' => $this->iUserId, 'user_box_id' => $this->userBoxId, 'type' => 0])
                ->select();
        if ($cart_goods) {
            //判断库存
            foreach ($cart_goods as &$val) {
                $goods_info = db('user_box_goods')
                        ->alias('ubg')
                        ->field('ubg.stock_num,ubg.selling_price,g.goods_id,g.goods_title,g.goods_model,g.goods_spec,g.goods_logo,gb.brand_title')
                        ->join('fa_goods g', 'g.goods_id = ubg.goods_id')
                        ->join('fa_goods_brand gb', 'g.brand_id = gb.brand_id')
                        ->where(['ubg.user_box_id' => $this->userBoxId, 'ubg.box_goods_id' => $val['box_goods_id'], 'ubg.is_del' => 0, 'g.status' => 1])
                        ->find();


                if (empty($goods_info)) {
                    $this->error('订单中有商品不存在');
                }

                $val['selling_price'] = $goods_info['selling_price'];
                $val['goods_id'] = $goods_info['goods_id'];
                $val['goods_title'] = $goods_info['goods_title'];
                $val['goods_model'] = $goods_info['goods_model'];
                $val['goods_spec'] = $goods_info['goods_spec'];
                $val['goods_logo'] = $goods_info['goods_logo'];
                $val['brand_title'] = $goods_info['brand_title'];
            }
            unset($val);
        } else {
            $this->error('没有要结算的商品');
        }

        $total_price = db('cart')
                ->fieldRaw('SUM(buy_num*ubg.selling_price) as total_price')
                ->alias('c')
                ->join('fa_user_box_goods ubg', 'ubg.box_goods_id = c.box_goods_id')
                ->where(['c.user_id' => $this->iUserId, 'c.user_box_id' => $this->userBoxId, 'c.type' => 0, 'ubg.is_del' => 0])
                ->find();


        $total_price = $total_price ? $total_price['total_price'] : 0;

        //抵扣前不能为0
        if ($total_price == 0) {
            $this->error('请确认商品正确');
        }

        $data['user_box_id'] = $this->userBoxId;
        $data['user_id'] = $this->iUserId;
        $data['goods_price'] = $total_price;
        Db::startTrans();
        try {

            if ($coupon_id != 0) {
                $coupon_info = db('user_coupon')
                        ->alias('uc')
                        ->field('uc.*,c.coupon_name,c.par_value,c.use_condition,c.range,c.relation_id')
                        ->join('fa_coupon c', 'uc.coupon_id = c.coupon_id')
                        ->where('uc.status', 0)
                        ->where('user_id', $this->iUserId)
                        ->where('user_coupon_id', $coupon_id)
                        ->order('user_coupon_id desc')
                        ->find();

                $coupon_discount = 0;
                if ($coupon_info) {

                    if ($coupon_info['range'] == 0) {
                        if ($total_price >= $coupon_info['use_condition']) {
                            $coupon_discount = 1;
                        }
                    }

                    if ($coupon_info['range'] == 1) {
                        $goods_total = db('cart')
                                ->fieldRaw('SUM(c.buy_num*ubg.selling_price) as total_price')
                                ->alias('c')
                                ->join('user_box_goods ubg', 'c.box_goods_id=ubg.box_goods_id')
                                ->join('goods g', 'ubg.goods_id=g.goods_id')
                                ->join('goods_brand gb', 'g.brand_id=gb.brand_id')
                                ->where('c.user_id', $this->iUserId)
                                ->where('c.user_box_id', $this->userBoxId)
                                ->where('c.type', 0)
                                ->where('gb.brand_id', 'in', $coupon_info['relation_id'])
                                ->find();

                        if ($total_price >= $coupon_info['use_condition']) {
                            $coupon_discount = 1;
                        }
                    }

                    if ($coupon_info['range'] == 2) {
                        $goods_total = db('cart')
                                ->fieldRaw('SUM(c.buy_num*ubg.selling_price) as total_price')
                                ->alias('c')
                                ->join('user_box_goods ubg', 'c.box_goods_id=ubg.box_goods_id')
                                ->join('goods g', 'ubg.goods_id=g.goods_id')
                                ->join('goods_cate gc', 'g.cate_id=gc.cate_id')
                                ->where('c.user_id', $this->iUserId)
                                ->where('c.user_box_id', $this->userBoxId)
                                ->where('c.type', 0)
                                ->where('gc.cate_id', 'in', $val['relation_id'])
                                ->find();

                        if ($goods_total['total_price'] >= $val['use_condition']) {
                            $coupon_discount = 1;
                        }
                    }
                }

                if ($coupon_discount) {

                    if ($total_price <= $coupon_info['par_value']) {
                        $data['coupon_discount'] = $total_price;
                        $total_price = 0;
                    } else {
                        $total_price -= $coupon_info['par_value'];
                        $data['coupon_discount'] = $coupon_info['par_value'];
                    }

                    $data['coupon_id'] = $coupon_id;

                    $use_coupon['usetime'] = date('Y-m-d H:i:s');
                    $use_coupon['status'] = 1;

                    db('user_coupon')->where('status', 0)
                            ->where('user_id', $this->iUserId)
                            ->where('user_coupon_id', $coupon_id)
                            ->update($use_coupon);
                }
            }

            $jifen_config = db('configure')->where(['key' => 'jifen'])->value('desc');
            $jifen_config = json_decode($jifen_config, true);

            if ($total_price > 0) {

                //是否使用积分抵扣
                if ($is_score) {
                    $user_info = db('users')->where(['user_id' => $this->iUserId])->find();

                    $score_discount = $user_info['score'] / $jifen_config['dikou'];

                    if ($total_price < $score_discount) {
                        $score_discount = $total_price;
                    }
                    $data['score_discount'] = $score_discount;
                    $total_price -= $score_discount;
                    $data['discount_score_num'] = $score_discount * $jifen_config['dikou'];
                }
            }

            $data['real_price'] = $total_price;
            $is_pay = 1; //是否需要支付
            //如果抵扣完以后订单金额为0  直接支付成功
            if ($total_price == 0) {
                $data['pay_type'] = 2;
                $data['is_pay'] = 1;
                $data['status'] = 10;
                $data['pay_at'] = date('Y-m-d H:i:s', time());
                $data['pay_price'] = 0;

                $is_pay = 0;
            }

            $data['give_score'] = $total_price * $jifen_config['zengsong'];

            $data['order_no'] = 'SO' . time() . mt_rand(1000, 9999);

            $order_id = db('order')->insertGetId($data);

            //扣除积分
            if ($is_score) {
                $score_discount = $data['score_discount'];

                $dikou_num = $score_discount * $jifen_config['dikou'];

                if ($dikou_num >= 0) {
                    db('users')->where(['user_id' => $this->iUserId])->setDec('score', $dikou_num);

                    $score_log['change_amount'] = $dikou_num;
                    $score_log['change_matters'] = 4;
                    $score_log['change_type'] = 1;
                    $score_log['user_id'] = $this->iUserId;
                    $score_log['order_id'] = $order_id;
                    $score_log['balance'] = $user_info['score'] - $dikou_num;

                    db('score_log')->insert($score_log);
                }
            }

            //添加库存变动流水
            $stock_log['change_type'] = 1;
            $stock_log['change_matters'] = 3;
            $stock_log['order_id'] = $order_id;
            foreach ($cart_goods as &$row) {
                $row['order_id'] = $order_id;
                $box_goods_id = $row['box_goods_id'];

                //更新库存和销量
                $user_box_info = db('user_box_goods')->where(['box_goods_id' => $box_goods_id, 'user_box_id' => $this->userBoxId])->find();
                if ($user_box_info['stock_num'] >= $row['buy_num']) {
                    $row['is_callback'] = $row['buy_num'];
                    db('user_box_goods')->where(['box_goods_id' => $box_goods_id, 'user_box_id' => $this->userBoxId])->setDec('stock_num', $row['buy_num']);
                } else {
                    $row['is_callback'] = $user_box_info['stock_num'];
                    db('user_box_goods')->where(['box_goods_id' => $box_goods_id, 'user_box_id' => $this->userBoxId])->update(['stock_num' => 0]);
                }
                
                $stock_log['box_goods_id'] = $box_goods_id;
                $stock_log['goods_id'] = $row['goods_id'];
                $stock_log['change_amount'] = $row['is_callback'];
                $stock_log['quantity'] = $user_box_info['stock_num'];
                
                db('stock_log')->insert($stock_log);
                
//                unset($row['box_goods_id']);
                db('order_goods')->insert($row);
            }

            //删除购物车
            db('cart')->where(['user_id' => $this->iUserId, 'user_box_id' => $this->userBoxId, 'type' => 0])->delete();

            Db::commit();

            $url = '';
            if ($is_pay == 1) {
                $url = url('selPay', array('out_trade_no' => $data['order_no']));
            } else {
                //TODO 更新小区商品销量
                $order_goods_list = db('order_goods')->where('order_id', $order_id)->select();

                if ($order_goods_list) {
                    $user_box_info = db('user_box')
                            ->where(['user_box_id' => $this->userBoxId, 'status' => 1])
                            ->find();
                    foreach ($order_goods_list as $row) {
                        db('house_goods')->where('goods_id', $row['goods_id'])->where('house_id', $user_box_info['quarters_id'])->setInc('sale_num', $row['buy_num']);
                    }
                }

                $url = url('payStatus', array('out_trade_no' => $data['order_no']));
            }

            $this->success('下单成功', ['url' => $url]);
        } catch (Exception $ex) {
            Db::rollback();
            $this->error('下单失败');
        }
    }

    //选择付款方式
    public function selPay() {
        $out_trade_no = $this->request->param('out_trade_no');
        $type = $this->request->param('type', 0);

        if (empty($out_trade_no)) {
            $this->error('请选择订单');
        }

        $order_info = db('order')->where(['order_no' => $out_trade_no])->find();
        $wallet = db('wallet')->where(['user_id' => $this->iUserId])->find();
        if (empty($wallet)) {
            $wallet['balance'] = 0.00;
        }
        //获取banner列表
//        $banner_list = db('ad')
//                ->where(['postion_id' => 2, 'type' => 1])
//                ->select();

        $banner_list = db('ad')
                ->alias('a')
                ->join('fa_ad_item ai', 'a.ad_id = ai.ad_id AND ai.position = 3', 'inner')
                ->where(['a.status' => 1, 'type' => 1])
                ->select();

        //订单结束时间

        $order_create_time = strtotime($order_info['createtime']);
        $order_end_time = date('Y/m/d H:i:s', $order_create_time + (5 * 60));

        $end_second = $order_create_time + (5 * 60) - time();
        if ($end_second < 0) {
            $end_second = 0;
        }

        $this->assign('type', $type);
        $this->assign('is_end_time', $end_second);
        $this->assign('order_end_time', $order_end_time);
        $this->assign('wallet', $wallet);
        $this->assign('banner_list', $banner_list);
        $this->assign('order_info', $order_info);

        return $this->view->fetch();
    }

    //去支付
    public function toPay() {
        $out_trade_no = $this->request->param('out_trade_no');
        $pay_type = $this->request->param('type', 1);

        if (empty($out_trade_no)) {
            $this->error('请选择支付订单');
        }

        if ($pay_type == 0) {
            $this->error('请选择支付方式');
        }

        $order_info = db('order')->where(['order_no' => $out_trade_no])->find();

        if ($order_info['status'] == 20) {
            $this->error('订单已关闭');
        }

        $url = '';
        if ($pay_type == 1) {
            $url = url('Wxpay/pay', array('out_trade_no' => $out_trade_no));
            $this->success('跳转支付', ['url' => $url]);
        } else {
            Db::startTrans();
            try {
                //余额支付
                $real_price = $order_info['real_price'];

                $order['pay_type'] = 2;
                $order['is_pay'] = 1;
                $order['status'] = 10;
                $order['pay_at'] = date('Y-m-d H:i:s', time());
                $order['pay_price'] = $real_price;

                db('order')->where(array('order_id' => $order_info['order_id'], 'user_id' => $this->iUserId))->update($order);

                $wallet_info = db('wallet')->where(array('user_id' => $this->iUserId))->find();
                if ($wallet_info['balance'] < $real_price) {
                    Db::rollback();
                    $this->error('支付失败,余额不足');
                }

                $wallet_data['updatetime'] = date('Y-m-d H:i:s', time());
                //优先使用赠送金额
                if ($wallet_info['give_amount'] >= $real_price) {
                    $wallet_data['give_amount'] = $wallet_info['give_amount'] - $real_price;
                } else {
                    $wallet_data['give_amount'] = 0;
                    $wallet_data['cash_amount'] = $wallet_info['cash_amount'] - ($real_price - $wallet_info['give_amount']);
                }
                $wallet_data['balance'] = $wallet_info['balance'] - $real_price;

                db('wallet')->where(array('wallet_id' => $wallet_info['wallet_id']))->update($wallet_data);

                $wlog['wallet_id'] = $wallet_info['wallet_id'];
                $wlog['change_amount'] = $real_price;
                $wlog['change_matters'] = 4;
                $wlog['change_type'] = 1;
                $wlog['order_id'] = $order_info['order_id'];

                db('wallet_log')->insert($wlog);

                //赠送积分
                $zengsong_num = $order_info['give_score'];

                if ($zengsong_num > 0) {
                    $user_info = db('users')->where(['user_id' => $this->iUserId])->find();
                    db('users')->where(['user_id' => $this->iUserId])->setInc('score', $zengsong_num);

                    $score_log['change_amount'] = $zengsong_num;
                    $score_log['change_matters'] = 1;
                    $score_log['change_type'] = 0;
                    $score_log['user_id'] = $this->iUserId;
                    $score_log['order_id'] = $order_info['order_id'];
                    $score_log['balance'] = $user_info['score'] + $zengsong_num;

                    db('score_log')->insert($score_log);
                }

                //TODO 更新小区商品销量
                $order_goods_list = db('order_goods')->where('order_id', $order_info['order_id'])->select();

                if ($order_goods_list) {
                    $user_box_info = db('user_box')
                            ->where(['user_box_id' => $order_info['user_box_id'], 'status' => 1])
                            ->find();
                    foreach ($order_goods_list as $row) {
                        db('house_goods')->where('goods_id', $row['goods_id'])->where('house_id', $user_box_info['quarters_id'])->setInc('sale_num', $row['buy_num']);
                    }
                }

                //领取满额优惠券
                $coupon_info = db('coupon')->where('receive_type', 2)->where('status', 1)->where('receive_type', '<=', $real_price)->order('receive_conf')->find();

                $coupon_count = db('user_coupon')->where('user_id', $this->iUserId)->where('coupon_id', $coupon_info['coupon_id'])->count();

                if ($coupon_count < $coupon_info['receive_num']) {
                    receiveCoupon($this->iUserId, $coupon_info['coupon_id']);
                }

                Db::commit();
                $url = url('payStatus', array('out_trade_no' => $out_trade_no));
                $this->success('支付成功', ['url' => $url]);
            } catch (Exception $ex) {
                Db::rollback();
                $this->error('余额支付失败');
            }
        }
    }

    public function payStatus() {
        $out_trade_no = $this->request->param('out_trade_no');
        $order_info = db('order')->where(['order_no' => $out_trade_no])->find();

        //获取banner列表
//        $banner_list = db('ad')
//                ->where(['postion_id' => 2, 'type' => 1])
//                ->select();

        $banner_list = db('ad')
                ->alias('a')
                ->join('fa_ad_item ai', 'a.ad_id = ai.ad_id AND ai.position = 4', 'inner')
                ->where(['a.status' => 1, 'type' => 1])
                ->select();


        $this->assign('order_info', $order_info);
        $this->assign('banner_list', $banner_list);
        return $this->view->fetch();
    }

    public function orderList() {

        $order_list = db('order')
                ->where(['user_id' => $this->iUserId, 'type' => 1])
                ->order('createtime desc')
                ->limit(10)
                ->select();

        if ($order_list) {
            foreach ($order_list as &$val) {
                $order_goods = db('order_goods')->where('order_id', $val['order_id'])->select();
                $val['goods_count'] = count($order_goods);

                if ($val['goods_count'] > 3) {
                    $order_goods = array_slice($order_goods, 0, 3);
                }
                $val['goods_list'] = $order_goods;
            }
            unset($val);
        } else {
            $order_list = [];
        }


        $this->assign('order_list', $order_list);
        return $this->view->fetch();
    }

    public function orderItem() {
        $p = $this->request->param('p', 0);
        $size = $this->request->param('psize', 6);
        $page = 0;
        if ($p) {
            $page = $p * $size;
        }

        $order_list = db('order')
                ->where(['user_id' => $this->iUserId, 'type' => 1])
                ->order('createtime desc')
                ->limit("$page,$size")
                ->select();

        if ($order_list) {
            foreach ($order_list as &$val) {
                $order_goods = db('order_goods')->where('order_id', $val['order_id'])->select();
                $val['goods_count'] = count($order_goods);

                if ($val['goods_count'] > 3) {
                    $order_goods = array_slice($order_goods, 0, 3);
                }

                $val['goods_list'] = $order_goods;
            }
            unset($val);
        } else {
            $order_list = [];
        }

        $this->assign('order_list', $order_list);
        return $this->view->fetch();
    }

    public function detail() {
        $order_id = $this->request->param('id', 0);
        $order_info = db('order')->where(array('order_id' => $order_id, 'user_id' => $this->iUserId))->find();

        if ($order_info) {
            $order_goods = db('order_goods')->where('order_id', $order_info['order_id'])->select();
            $order_info['goods_count'] = count($order_goods);
            $order_info['goods_list'] = $order_goods;
        } else {
            $order_info = [];
        }

        $this->assign('order_info', $order_info);
        return $this->view->fetch();
    }

    //申请盒子
    public function apply() {
        return $this->view->fetch();
    }

}
